package cn.com.anypay.gateway.suanzhu;

import cn.com.anypay.manager.common.response.ApiResponse;
import cn.com.anypay.manager.miaoma.paydeviceqrcode.PayDeviceQrcodeService;
import cn.com.anypay.manager.miaoma.paydeviceqrcode.PayDeviceQrcodeEntity;
import cn.com.anypay.manager.miaoma.paydeviceqrcode.dto.PayDeviceQrcodeDTO;
import cn.com.anypay.manager.miaoma.paydeviceqrcode.auto.AutoPayDeviceQrcodeUtils;
import cn.com.anypay.manager.miaoma.paymentappconfig.PaymentAppConfigService;
import cn.com.anypay.manager.miaoma.paymentappconfig.PaymentAppConfigEntity;
import cn.com.anypay.manager.miaoma.paymentappconfig.dto.PaymentAppConfigDTO;
import cn.com.anypay.manager.miaoma.paymentappconfig.auto.AutoPaymentAppConfigUtils;
import cn.com.anypay.manager.miaoma.merchantinfo.MerchantInfoService;
import cn.com.anypay.manager.miaoma.merchantinfo.MerchantInfoEntity;
import cn.com.anypay.manager.miaoma.merchantinfo.dto.MerchantInfoDTO;
import cn.com.anypay.manager.miaoma.merchantinfo.auto.AutoMerchantInfoUtils;
import cn.com.anypay.manager.miaoma.serviceprovider.ServiceProviderService;
import cn.com.anypay.manager.miaoma.serviceprovider.ServiceProviderEntity;
import cn.com.anypay.manager.miaoma.serviceprovider.dto.ServiceProviderDTO;
import cn.com.anypay.manager.miaoma.serviceprovider.auto.AutoServiceProviderUtils;
import cn.com.anypay.manager.miaoma.unifiedchannelconfig.UnifiedChannelConfigService;
import cn.com.anypay.manager.miaoma.unifiedchannelconfig.dto.UnifiedChannelConfigDTO;
import cn.com.anypay.gateway.suanzhu.dto.SuanzhuGatewayResponseDTO;

import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 算珠网关控制器
 * 处理二维码扫描后的信息查询和展示
 * 使用现有的Service和DTO，避免原始SQL查询
 */
@Controller
@RequestMapping("/api/suanzhu")
public class SuanzhuController {

    private static final Logger logger = LoggerFactory.getLogger(SuanzhuController.class);

    /**
     * 微信JSAPI支付产品编码常量
     */
    private static final String WXPAY_JSAPI_PRODUCT_CODE = "WXPAY_JSAPI";

    @Autowired
    private PayDeviceQrcodeService payDeviceQrcodeService;

    @Autowired
    private PaymentAppConfigService paymentAppConfigService;

    @Autowired
    private MerchantInfoService merchantInfoService;

    @Autowired
    private ServiceProviderService serviceProviderService;

    @Autowired
    private UnifiedChannelConfigService unifiedChannelConfigService;

    /**
     * 算珠网关健康检查
     */
    @GetMapping("/health")
    @ResponseBody
    public ApiResponse<String> health() {
        return ApiResponse.success("算珠网关运行正常");
    }

    /**
     * 根据二维码ID获取相关信息
     * 包括二维码信息、应用配置、商户信息、服务商信息
     */
    @GetMapping("/qrcode/entry")
    @ResponseBody
    public ApiResponse<SuanzhuGatewayResponseDTO> getQrcodeInfo(@RequestParam String qrcode) {
        try {
            if (qrcode == null || qrcode.trim().isEmpty()) {
                return ApiResponse.fail("二维码ID不能为空");
            }

            logger.info("开始查询算珠网关二维码信息, qrcode: {}", qrcode);

            SuanzhuGatewayResponseDTO.SuanzhuGatewayResponseDTOBuilder responseBuilder =
                SuanzhuGatewayResponseDTO.builder();

            // 1. 查询二维码信息
            PayDeviceQrcodeEntity qrcodeEntity = payDeviceQrcodeService.getById(qrcode);
            PayDeviceQrcodeDTO qrcodeInfo = AutoPayDeviceQrcodeUtils.convertEntityToDTO(qrcodeEntity);
            responseBuilder.qrcodeInfo(qrcodeInfo);

            if (qrcodeInfo == null) {
                logger.warn("未找到二维码信息: {}", qrcode);
                responseBuilder.error("未找到二维码信息，请检查二维码ID是否正确");
                return ApiResponse.success(responseBuilder.build());
            }

            // 2. 根据二维码信息中的appId查询应用配置信息
            String appId = qrcodeInfo.getAppId();
            if (appId != null) {
                PaymentAppConfigEntity appEntity = paymentAppConfigService.getById(appId);
                PaymentAppConfigDTO appInfo = AutoPaymentAppConfigUtils.convertEntityToDTO(appEntity);
                responseBuilder.appInfo(appInfo);

                if (appInfo != null) {
                    // 3. 查询WXPAY_JSAPI产品的渠道配置
                    queryChannelConfigs(responseBuilder, appInfo);

                    // 4. 根据应用配置中的merchantId查询商户信息
                    String merchantId = appInfo.getMerchantId();
                    if (merchantId != null) {
                        MerchantInfoEntity merchantEntity = merchantInfoService.getById(merchantId);
                        MerchantInfoDTO merchantInfo = AutoMerchantInfoUtils.convertEntityToDTO(merchantEntity);
                        responseBuilder.merchantInfo(merchantInfo);

                        if (merchantInfo != null) {
                            // 5. 根据商户信息中的providerId查询服务商信息
                            String providerId = merchantInfo.getProviderId();
                            if (providerId != null) {
                                ServiceProviderEntity providerEntity = serviceProviderService.getById(providerId);
                                ServiceProviderDTO serviceProviderInfo = AutoServiceProviderUtils.convertEntityToDTO(providerEntity);
                                responseBuilder.serviceProviderInfo(serviceProviderInfo);
                            }
                        }
                    }
                }
            }

            SuanzhuGatewayResponseDTO response = responseBuilder.build();
            logger.info("算珠网关二维码信息查询完成, qrcode: {}", qrcode);
            return ApiResponse.success(response);

        } catch (Exception e) {
            logger.error("查询二维码信息失败, qrcode: {}, error: {}", qrcode, e.getMessage(), e);
            return ApiResponse.fail("查询二维码信息失败: " + e.getMessage());
        }
    }

    /**
     * 查询渠道配置信息
     * 根据应用的连接模式查询相应的渠道配置
     *
     * @param responseBuilder 响应构建器
     * @param appInfo 应用配置信息
     */
    private void queryChannelConfigs(SuanzhuGatewayResponseDTO.SuanzhuGatewayResponseDTOBuilder responseBuilder, PaymentAppConfigDTO appInfo) {
        try {
            String appId = appInfo.getAppId();
            Integer connectMode = appInfo.getConnectMode();

            logger.info("开始查询渠道配置, appId: {}, connectMode: {}", appId, connectMode);

            // 1. 查询应用产品配置
            UnifiedChannelConfigDTO productConfig = unifiedChannelConfigService.getAppProductConfig(appId);
            if (productConfig == null) {
                logger.warn("未找到应用产品配置, appId: {}", appId);
                return;
            }

            // 2. 从产品配置中提取WXPAY_JSAPI的渠道编码
            String configDataJson = productConfig.getConfigData();
            String channelCode = unifiedChannelConfigService.extractChannelCodeFromConfigData(configDataJson, WXPAY_JSAPI_PRODUCT_CODE);
            if (channelCode == null) {
                logger.warn("未找到WXPAY_JSAPI产品的渠道编码, appId: {}", appId);
                return;
            }

            logger.info("提取到渠道编码, appId: {}, channelCode: {}", appId, channelCode);

            if (connectMode == 2) {
                // 间连模式：查询服务商渠道配置和子商户渠道配置
                String merchantId = appInfo.getMerchantId();
                if (merchantId != null) {
                    // 通过merchantId查询商户信息，获取服务商ID
                    MerchantInfoEntity merchantEntity = merchantInfoService.getById(merchantId);
                    if (merchantEntity != null) {
                        String providerId = merchantEntity.getProviderId();
                        if (providerId != null) {
                            // 查询服务商渠道配置
                            UnifiedChannelConfigDTO providerConfig = unifiedChannelConfigService.getServiceProviderChannelConfig(providerId, channelCode);
                            if (providerConfig != null) {
                                responseBuilder.serviceProviderChannelConfig(providerConfig);
                                logger.info("找到服务商渠道配置, configId: {}, providerId: {}, channelCode: {}",
                                           providerConfig.getConfigId(), providerId, channelCode);
                            } else {
                                logger.warn("未找到服务商渠道配置, providerId: {}, channelCode: {}", providerId, channelCode);
                            }
                        }
                    }
                }

                // 查询子商户渠道配置
                UnifiedChannelConfigDTO subMerchantConfig = unifiedChannelConfigService.getSubMerchantChannelConfig(appId, channelCode);
                if (subMerchantConfig != null) {
                    responseBuilder.subMerchantChannelConfig(subMerchantConfig);
                    logger.info("找到子商户渠道配置, configId: {}, appId: {}, channelCode: {}",
                               subMerchantConfig.getConfigId(), appId, channelCode);
                } else {
                    logger.warn("未找到子商户渠道配置, appId: {}, channelCode: {}", appId, channelCode);
                }

            } else if (connectMode == 1) {
                // 直连模式：查询直连商户渠道配置
                UnifiedChannelConfigDTO directMerchantConfig = unifiedChannelConfigService.getDirectMerchantChannelConfig(appId, channelCode);
                if (directMerchantConfig != null) {
                    responseBuilder.directMerchantChannelConfig(directMerchantConfig);
                    logger.info("找到直连商户渠道配置, configId: {}, appId: {}, channelCode: {}",
                               directMerchantConfig.getConfigId(), appId, channelCode);
                } else {
                    logger.warn("未找到直连商户渠道配置, appId: {}, channelCode: {}", appId, channelCode);
                }
            } else {
                logger.warn("未知的连接模式: {}", connectMode);
            }

        } catch (Exception e) {
            logger.error("查询渠道配置失败, appId: {}, error: {}", appInfo.getAppId(), e.getMessage(), e);
        }
    }
}